import random
from flask import Blueprint, jsonify, render_template, session
from config import db
from models.models import History, GoodsType, Goods
from sqlalchemy import func

analytics_service = Blueprint("analytics_service", __name__)


@analytics_service.before_request
def session_checker():
    if 'user_id' not in session:
        return render_template('401.html')


@analytics_service.route("/user_preferences")
def user_preferences():
    type_counts = db.session.query(History.type, func.count(History.type)).group_by(History.type).all()
    data = []
    for type, count in type_counts:
        if type != 0:
            goodstype = GoodsType.query.filter_by(id=type).first()
            data.append({
                'value': count,
                'name': goodstype.name
            })
    option = {
        'series': [
            {
                'type': 'pie',
                'data': data
            }
        ]
    }
    return jsonify(option)


@analytics_service.route("/get/preferences")
def preferences():
    return render_template('user_analytics.html')
